#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cv2
import logging

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def check_camera_support():
    """
    检查OpenCV支持的摄像头后端
    """
    logger.info("检查OpenCV版本和支持的后端...")
    logger.info(f"OpenCV版本: {cv2.__version__}")
    
    # 尝试列出支持的后端
    backends = []
    backend_attrs = [attr for attr in dir(cv2) if attr.startswith('CAP_')]
    logger.info("支持的后端属性:")
    for attr in backend_attrs:
        logger.info(f"  {attr}: {getattr(cv2, attr)}")
    
    # 尝试打开摄像头
    logger.info("尝试打开摄像头...")
    
    # 尝试不同的后端
    test_backends = [
        ('默认', -1),
        ('ANY', cv2.CAP_ANY if hasattr(cv2, 'CAP_ANY') else -1),
        ('V4L2', cv2.CAP_V4L2 if hasattr(cv2, 'CAP_V4L2') else -1),
        ('LIBCAMERA', cv2.CAP_LIBCAMERA if hasattr(cv2, 'CAP_LIBCAMERA') else -1),
    ]
    
    for name, backend in test_backends:
        if backend == -1:
            continue
            
        try:
            logger.info(f"尝试使用 {name} 后端 (值: {backend})")
            if backend == -1:
                cap = cv2.VideoCapture(0)
            else:
                cap = cv2.VideoCapture(0, backend)
            
            if cap.isOpened():
                logger.info(f"  成功使用 {name} 后端打开摄像头")
                width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
                height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
                fps = cap.get(cv2.CAP_PROP_FPS)
                logger.info(f"  分辨率: {width}x{height}, FPS: {fps}")
                
                # 尝试读取一帧
                ret, frame = cap.read()
                if ret:
                    logger.info(f"  成功读取帧，尺寸: {frame.shape}")
                else:
                    logger.warning(f"  无法读取帧")
                
                cap.release()
                break
            else:
                logger.warning(f"  无法使用 {name} 后端打开摄像头")
            cap.release()
        except Exception as e:
            logger.error(f"  使用 {name} 后端时出错: {e}")

def test_camera_read():
    """
    测试摄像头读取功能
    """
    logger.info("测试摄像头读取功能...")
    cap = cv2.VideoCapture(0)
    
    if not cap.isOpened():
        logger.error("无法打开摄像头")
        return False
    
    # 读取几帧
    for i in range(10):
        ret, frame = cap.read()
        if ret:
            logger.info(f"成功读取第 {i+1} 帧，尺寸: {frame.shape}")
        else:
            logger.warning(f"无法读取第 {i+1} 帧")
    
    cap.release()
    return True

if __name__ == "__main__":
    check_camera_support()
    test_camera_read()